package com.ruoyi.web.controller.basicInformation;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.TShipTree;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.basicInformation.domain.TShip;
import com.ruoyi.system.basicInformation.service.ITTerminalService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.basicInformation.vo.TShipVo;
import com.ruoyi.system.basicInformation.bo.TShipQueryBo;
import com.ruoyi.system.basicInformation.bo.TShipAddBo;
import com.ruoyi.system.basicInformation.bo.TShipEditBo;
import com.ruoyi.system.basicInformation.service.ITShipService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

/**
 * 船舶信息Controller
 * 
 * @author ruoyi
 * @date 2021-05-20
 */
@Api(value = "船舶信息控制器", tags = {"船舶信息管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/basicInformation/ship")
public class TShipController extends BaseController {

    private final ITShipService iTShipService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ITTerminalService terminalService;

    /**
     * 查询船舶信息列表
     */
    @ApiOperation("查询船舶信息列表")
    @PreAuthorize("@ss.hasPermi('basicInformation:ship:list')")
    @GetMapping("/list")
    public TableDataInfo<TShipVo> list(TShipQueryBo bo) {
        startPage();
        List<TShipVo> list = iTShipService.queryList(bo);
        return getDataTable(list);
    }

    /**
     * 查询船舶最后定位信息列表
     */
    @ApiOperation("查询船舶最后定位信息列表")
//    @PreAuthorize("@ss.hasPermi('basicInformation:ship:list')")
    @GetMapping("/currentPoint")
    public TableDataInfo<TShipVo> currentPoint(TShipQueryBo bo) {
        startPage();
        List<TShipVo> list = iTShipService.listShipCurrentPoint(bo);
        return getDataTable(list);
    }
    /**
     * 查询船舶信息列表
     */
    @ApiOperation("在船人数统计")
    @PreAuthorize("@ss.hasPermi('basicInformation:ship:personnelStatistics')")
    @GetMapping("/listShipPersonnelStatistics")
    public TableDataInfo<TShipVo> listShipPersonnelStatistics(TShipQueryBo bo) {
        startPage();
        List<TShipVo> list = iTShipService.listShipPersonnelStatistics(bo);
        return getDataTable(list);
    }

    /**
     * 导出船舶信息列表
     */
    @ApiOperation("导出船舶信息列表")
    @PreAuthorize("@ss.hasPermi('basicInformation:ship:export')")
    @Log(title = "船舶信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<TShipVo> export(TShipQueryBo bo) {
        startPage();
        if(bo.getIds() != null && bo.getIds().length>0)
        {
            bo.setUserIdsStr(StringUtils.join(bo.getIds(), ","));
        }
        List<TShipVo> list = iTShipService.queryList(bo);
        ExcelUtil<TShipVo> util = new ExcelUtil<TShipVo>(TShipVo.class);
        String msg="船舶信息";
        if(bo.getShipType().equals("2"))
        {
            msg="执法船舶信息";
        }
        return util.exportExcel(list, msg);
    }

    @Log(title = "船舶信息管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('basicInformation:ship:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String shipType) throws Exception
    {
        ExcelUtil<TShip> util = new ExcelUtil<TShip>(TShip.class);
        List<TShip> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = iTShipService.importUser(userList, updateSupport, operName, shipType);
        return AjaxResult.success(message);
    }


    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<TShip> util = new ExcelUtil<TShip>(TShip.class);
        return util.importTemplateExcel("船舶信息模板数据");
    }

    /**
     * 获取船舶信息详细信息
     */
    @ApiOperation("获取船舶信息详细信息")
    @PreAuthorize("@ss.hasPermi('basicInformation:ship:query')")
    @GetMapping("/{id}")
    public AjaxResult<TShipVo> getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iTShipService.queryById(id));
    }

    /**
     * 新增船舶信息
     */
    @ApiOperation("新增船舶信息")
    @PreAuthorize("@ss.hasPermi('basicInformation:ship:add')")
    @Log(title = "船舶信息", businessType = BusinessType.INSERT)
    @PostMapping()
    public AjaxResult<Void> add(@RequestBody TShipAddBo bo) {
        int result =iTShipService.insertByAddBo(bo) ? 1 : 0;
                //绑定终端
        //terminalService.updateTerminalByObjId(bo.getTerminalId(),bo.getId());
        return toAjax(result);
    }

    /**
     * 解绑终端设备
     */
    @ApiOperation("解绑终端设备")
    @PreAuthorize("@ss.hasPermi('basicInformation:ship:edit')")
    @Log(title = "解绑终端设备", businessType = BusinessType.UPDATE)
    @PostMapping("/unBundling")
    public AjaxResult<Void> unBundling(@RequestBody TShipEditBo bo) {
        return toAjax(terminalService.unBundling(bo.getTerminalId()) ? 1 : 0);
    }

    /**
     * 修改船舶信息
     */
    @ApiOperation("修改船舶信息")
    @PreAuthorize("@ss.hasPermi('basicInformation:ship:edit')")
    @Log(title = "船舶信息", businessType = BusinessType.UPDATE)
    @PutMapping()
    public AjaxResult<Void> edit(@RequestBody TShipEditBo bo) {
        //绑定终端
        if(bo.getTerminalId()!=bo.getTerminalIdOld())
        {
            terminalService.unBundling(bo.getTerminalIdOld());
        }

        terminalService.updateTerminalByObjId(bo.getTerminalId(),bo.getId());
        return toAjax(iTShipService.updateByEditBo(bo) ? 1 : 0);
    }

    /**
     * 删除船舶信息
     */
    @ApiOperation("删除船舶信息")
    @PreAuthorize("@ss.hasPermi('basicInformation:ship:remove')")
    @Log(title = "船舶信息" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@PathVariable Long[] ids) {
        for (int i = 0; i < ids.length; i++) {

            TShipVo tCarVo=  iTShipService.queryById(ids[i]);
            if(tCarVo.getTerminalId()!=null){
                terminalService.unBundling(tCarVo.getTerminalId().longValue());
            }
        }
        return toAjax(iTShipService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    @GetMapping("/treeselect")
    public AjaxResult treeselect(TShipTree dept)
    {
        return AjaxResult.success(iTShipService.selectShipList(dept));
    }
}
